package io.yunho.srw.pwebflux.routerfunction.config;

import io.yunho.srw.pwebflux.routerfunction.handler.UserHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

/**
 * @author: yunho
 * @date: 2021/5/13 15:02
 * @description: 类似于spring mvc的dispatch
 * 是将用户的uri和router function对应起来
 */
@Configuration
public class AllRouters {

    @Bean
    RouterFunction<ServerResponse> userRouter(UserHandler userHandler) {
        //注意引入包的时候要引用org.springframework.web.reactive下的对象
        return RouterFunctions
                //嵌套
                .nest(
                        //相当于@RequestMapping("/user")
                        RequestPredicates.path("/ruser"),
                        //相当于@GetMapping(value = "/")
                        RouterFunctions.route(
                                //获取所有用户
                                RequestPredicates.GET("/"),
                                userHandler::getAllUserHandle
                        )
                                .andRoute(
                                        //新增用户
                                        RequestPredicates.POST("/")
                                                .and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
                                        userHandler::putUserHandle
                                )
                                .andRoute(
                                        RequestPredicates.DELETE("/{id}"),
                                        userHandler::deleteUserHandle
                                )
                                .andRoute(
                                        RequestPredicates.GET("/{id}"),
                                        userHandler::getUserHandle
                                )
                );
    }
}
